package com.dc.adaptor.transport.jms;


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.dc.trans.steps.xmlpackagetransform.biz.OutZjzx2TaxTransform;

public class JmsManager {
	private static JmsManager manager = null;

	public JmsManager() {
	}

	public static JmsManager getInstance() {
		if (manager == null) {
			manager = new JmsManager();
			new FileSystemXmlApplicationContext("etc/spring/jms.xml");
		}
		return manager;
	}

	public void send(String xml) {
		OutZjzx2TaxTransform s = new OutZjzx2TaxTransform();
		try {
			xml = s.execute(xml);
			System.out.println("TaxXml:-->" + xml);
			sendx(xml);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void sendx(String str) throws NamingException, JMSException, IOException {
		String JNDIFactory = "weblogic.jndi.WLInitialContextFactory";
		Properties prop = new Properties();
		InputStream in = new BufferedInputStream(new FileInputStream("etc/spring/jms.properties"));
		prop.load(in);
		String providerUrl = prop.getProperty("wbjh.jms.send.url");
		String connFactoryJNDI = prop.getProperty("wbjh.jms.factory.send.jndiName");
		String queueJNDI = prop.getProperty("wbjh.jms.queue.send.jndiName");

		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, JNDIFactory);
		env.put(Context.PROVIDER_URL, providerUrl);
		Context ctx = new InitialContext(env);

		// connectionFactory JNDI name
		QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(connFactoryJNDI);
		// create queue connection
		QueueConnection qConn = (QueueConnection) connFactory.createConnection();
		// create session
		QueueSession qSession = qConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
		// find queue by JNDI lookup
		Queue queue = (Queue) ctx.lookup(queueJNDI);
		// create sender
		QueueSender qSender = qSession.createSender(queue);
		// create message
		Message msg = qSession.createTextMessage(str);
		qSender.send(msg);
		qSender.close();
		qSession.close();
		qConn.close();
	}
}